package com.example.cafe.work.service.impl;

import com.example.cafe.work.dto.OrderDisplay;
import com.example.cafe.work.dto.Result;
import com.example.cafe.work.model.Coffee;
import com.example.cafe.work.model.Order;
import com.example.cafe.work.mapper.OrderMapper;
import com.example.cafe.work.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cafe.work.util.RedisIdWorker;
import com.example.cafe.work.util.Uuid;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hua
 * @since 2024-09-16
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    RedisIdWorker redisIdWorker;
    @Resource
    OrderMapper orderMapper;

    @Override
    public Result createOrder(List<Coffee> coffee, String userId) {
        //传的是list，list中有几个对象就添加几条订单
        long count = coffee.size();
        long result=0;
        //传回的都是前端展示的，不加判断，直接读取数据，order_id随机
        for (Coffee coffee1 : coffee) {
            long id = redisIdWorker.nextId("order");
            String orderId = Long.toString(id);
            String cofId = coffee1.getCofId();
            int total = coffee1.getQuantity()*coffee1.getCofPrice();
            boolean save = save(new Order(orderId, userId, cofId, coffee1.getQuantity(), total, Uuid.getTime()));
            if(save){result++;}else throw new RuntimeException("创建订单异常");
        }
        return Result.ok(count==result);
    }

    @Override
    public Result queryOrder(String state, String userId, int page, int size) {
        //分页
        int start = page*size-size;
        //自定义sql，tmd四张表联查，
        List<OrderDisplay> orderDisplay = orderMapper.queryOrder(state, userId, start, size);
        return Result.ok(orderDisplay);
    }
}
